import React from 'react' 
export default class App2 extends React.Component{
    constructor(props) {
        super(props) 
        this.state = {
            comments:[
             
            ],
            userContent:'',
            userName:''
        }
    }

    // react中多表单共用改变数据的方法 
    handleForm =(e)=>{
        this.setState({
            // userName
            //userContent
            [e.target.name]:e.target.value
        },()=>{
            console.log('userContent',this.state.userContent)
            console.log('userName',this.state.userName)
        })
    }
        
    // 点击发表评论方法 
    addComment=()=>{
        const {comments,userContent,userName} = this.state 
        if(userName.trim()==='' || userContent.trim()==='') {
            alert('请您填写完整')
            return 
        }
        const newComments = [
            {
                id:Math.random(),
                name:userName,
                content:userContent
            },
            ...comments
        ]

        this.setState({
            comments:newComments,
            userContent:'',
            userName:''
        })
    }



    render () {
        return (
            <div>
                <div>
                    <input 
                    name='userName'
                    onChange={this.handleForm}
                    type='text' 
                    value={this.state.userName}
                    placeholder='请输入评论人'/> <br/>
                    <textarea
                        cols='50'
                        rows='10'
                        name='userContent'
                        onChange={this.handleForm}
                        value={this.state.userContent}
                    ></textarea>
                </div>
                <button onClick={this.addComment}>点击提交</button>
                <div>
                    
                    <ul>
                        {
                            this.state.comments.length == 0 ? 
                            (
                                <div>暂无评论,快去评论吧</div>
                            ) :(
                                this.state.comments.map(item=>(
                                    <li key={item.id}>
                                        <h2>评论人: {item.name}</h2>
                                        <p>评论内容: {item.content}</p>
                                    </li>
                                ))
                            )
                        } 
                    </ul>
                </div>
            </div>
        )
    }
}